<?php

namespace Phpben\Imi\ConfigCenter\Process;

use Imi\Log\Log;
use Imi\Swoole\Process\BaseProcess;
use Imi\Swoole\Process\Annotation\Process;
use Imi\Config;
use Imi\App;
use Exception;
use Imi\Swoole\Server\Server;

/**
 * 配置中心
 * @Process(name="config_center")
 */
class ConfigCenterProcess extends BaseProcess
{

    /**
     * 同步配置
     * @param \Swoole\Process $process
     */
    public function run(\Swoole\Process $process): void
    {
        while (true) {
            $config = Config::get('@app.beans.ConfigCenter');
            $interval = (int)$config['interval'];
            $rowConfig = Config::get("@app.website");
            try {
                $driver = new $config['driver'];
                $getConfig = (array)$driver->get();
                Server::sendMessage('config_center', [
                    'configs' => $getConfig
                ]);
                $servers = (array)Config::get('@app.subServers');
                foreach ($servers as $k => $v) {
                    Server::sendMessage('config_center', [
                        'configs' => $getConfig
                    ], null, (string)$k);
                }
                sleep($interval);
            } catch (Exception $e) {
                Log::error("[" . $e->getFile() . "]:(" . $e->getLine() . ") " . $e->getMessage());
            }
        }
    }

}